package user

import (
	"context"
	"my-zero-tiktok/apps/user/pb/pb"
	"my-zero-tiktok/common/auth"
	"my-zero-tiktok/common/xerr"
	"time"

	"my-zero-tiktok/apps/api/internal/svc"
	"my-zero-tiktok/apps/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Register 注册
func (l *RegisterLogic) Register(req *types.RegisterRequest) (resp *types.TokenResponse, err error) {
	user, err := l.svcCtx.UserRPC.CreateUser(l.ctx, &pb.NamePassRequest{Name: req.Name, Password: req.Password})
	if err != nil {
		return nil, err
	}

	now := time.Now().Unix()
	secret := l.svcCtx.Config.Auth.AccessSecret
	expire := l.svcCtx.Config.Auth.AccessExpire
	payload := map[string]interface{}{"id": user.Id}
	accessToken, err := auth.GenToken(now, secret, payload, expire)
	if err != nil {
		return nil, xerr.New(xerr.GenTokenError)
	}
	return &types.TokenResponse{
		AccessToken:  accessToken,
		AccessExpire: now + expire,
		RefreshAfter: now + expire/2,
	}, nil
}
